<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表格管理</title>
    <link rel="stylesheet" href="/static/css/layui.css">
</head>

<body>

    <!-- 主体部分 -->
    <div class="layui-card">
        <div class="layui-card-body">

            <div class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <div class="layui-input-inline">
                            <input type="text" id="ID" name="ID" placeholder="编号" autocomplete="off"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button id="btn_search" class="layui-btn layui-icon  layui-icon-search" data-type="search">查询
                        </button>
                    </div>
                    <div class="layui-inline">
                        <button id="btn_refresh" class="layui-btn layui-icon  layui-icon-refresh" data-type="search">重置
                        </button>
                    </div>
                </div>

            </div>

            <table id="manage_table" lay-filter="manage_table"></table>
        </div>
    </div>

    <!-- 表格基本操作按钮 -->
    <script type="text/html" id="table_operation">
    <a class="layui-btn layui-btn-xs" lay-event="load">下载附件</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="submit">提交作业</a>
</script>
    <!--其他操作-->
    <script type="text/html" id="other_operation">

</script>

    <!-- javascript 脚本 -->
    <script src="/static/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'table'], function () {
            var table = layui.table;
            var
                $ = layui.jquery,
                table = layui.table,
                form = layui.form,
                layer = layui.layer;

            var currentRow = {},
                currentOpt = "",
                loadUrl = "/homework/load",
                submitUrl = "/homework/submit",
                listUrl = "/homework/list1",
                layerIndex = 0;

            $(function () {
                // 查询按钮
                $("#btn_search").on("click", function () {
                    table.reload('manage_table', {
                        where: {
                            ID: $("#ID").val()
                        }
                        , page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                });
                $("#btn_refresh").on("click", function () {
                    initTable();
                });
                initTable();
            });

            function initTable() {
                // 初始化列表(表格)
                table.render({
                    elem: '#manage_table'
                    , url: listUrl
                    , request: {
                        pageName: 'pageIndex',  // 页码的参数名称，默认：page
                        limitName: 'pageSize'   // 每页数据量的参数名，默认：limit
                    }
                    , page: {
                        layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
                        curr: 1,      // 设置默认起始页1s
                        groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
                        first: false, // 不显示首页
                        last: false   // 不显示尾页
                    }
                    , limits: [10, 20, 30, 40, 50]

                    , cols: [
                        [ //表头
                            { field: 'ID', title: '编号', align: 'center' }
                            , { field: 'title', title: '标题', align: 'center' }
                            , {
                                field: 'homework_type', title: '作业类型', align: 'center', templet: function (d) {
                                    return d.homework_type === 'text' ? '<span style="color: #01AAED;">文本作业</span>' : '<span style="color: #FF5722;">代码作业</span>';
                                }
                            }
                            , { field: 'h_content', title: '内容', align: 'center' }
                            , { field: 'issuedate', title: '发布时间', align: 'center' }
                            , { field: 'deadline', title: '截止时间', align: 'center' }
                            , { field: 'submit_limit', title: '提交次数限制', align: 'center' }
                            , { field: 'attachment_name', title: '附件名', align: 'center' }
                            , { field: 'answer', title: '答案', align: 'center' }
                            , { fixed: 'right', title: '操作', toolbar: '#table_operation', width: 200 }
                        ]
                    ],
                    parseData: function (res) { //res 即为原始返回的数据
                        console.log(res)
                        return {
                            "code": res.code == 200 ? 0 : res.code, //解析接口状态
                            "msg": res.code == 200 ? "" : res.msg, //解析提示文本
                            "count": res.count, //解析数据长度
                            "data": res.data //解析数据列表
                        };
                    }
                });

                // 绑定表格bar 按钮事件
                table.on('tool(manage_table)', function (obj) {
                    console.log(obj)
                    if (obj.event === 'load') {
                        currentRow = obj.data;
                        console.log(currentRow)
                        currentOpt = loadUrl;
                    } else if (obj.event === 'submit') {
                        currentRow = obj.data;
                        console.log(currentRow)
                        currentOpt = submitUrl;

                        // 根据作业类型创建不同的提交表单HTML
                        var homeworkType = currentRow.homework_type || 'code'; // 默认为代码作业
                        var submitFormHtml = '';

                        if (homeworkType === 'text') {
                            // 文本作业表单
                            submitFormHtml = `
                                <form class="layui-form" lay-filter="submit_form" id="submit_form" style="margin: 10px auto;">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">作业类型</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="submission_type" value="text" title="文本作业" checked>
                                        </div>
                                    </div>
                                    <div class="layui-form-item layui-form-text">
                                        <label class="layui-form-label">作业内容</label>
                                        <div class="layui-input-block">
                                            <textarea placeholder="请输入文本作业内容" class="layui-textarea" name="text_content" style="width: 600px; height:400px;margin: 10px auto"></textarea>
                                        </div>
                                    </div>
                                    <div class="layui-form-item" id="form_btn">
                                        <div class="layui-input-block">
                                            <button type="button" class="layui-btn" lay-submit lay-filter="post_form">立即提交</button>
                                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                        </div>
                                    </div>
                                </form>
                            `;
                        } else {
                            // 代码作业表单（原有逻辑）
                            submitFormHtml = `
                                <form class="layui-form" lay-filter="submit_form" id="submit_form" style="margin: 10px auto;">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">作业类型</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="submission_type" value="code" title="代码作业" checked>
                                        </div>
                                    </div>
                                    <div class="layui-form-item layui-form-text">
                                        <label class="layui-form-label">作业代码</label>
                                        <div class="layui-input-block">
                                            <textarea placeholder="请输入作业代码" class="layui-textarea" name="code" style="width: 600px; height:400px;margin: 10px auto"></textarea>
                                        </div>
                                    </div>
                                    <div class="layui-form-item" id="form_btn">
                                        <div class="layui-input-block">
                                            <button type="button" class="layui-btn" lay-submit lay-filter="post_form">立即提交</button>
                                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                        </div>
                                    </div>
                                </form>
                            `;
                        }

                        layerIndex = layer.open({
                            title: "提交作业源码",
                            type: 1,
                            shadeClose: true,
                            area: ['800px', '600px'],
                            content: submitFormHtml,
                            success: function (layero, index) {
                                console.log('弹窗打开成功，开始初始化表单');

                                // 弹窗打开后重新初始化表单
                                form.render();
                                form.val('submit_form', currentRow);

                                console.log('表单初始化完成，绑定提交事件');

                                // 生成唯一的事件标识符
                                var eventId = 'post_form_' + Date.now();

                                // 更新按钮的lay-filter属性
                                $(layero).find('button[lay-submit]').attr('lay-filter', eventId);

                                // 绑定表单提交事件
                                form.on('submit(' + eventId + ')', function (data) {
                                    console.log('=== 表单提交开始 ===');
                                    console.log('表单提交事件触发');
                                    console.log('表单数据:', data.field);
                                    console.log('当前行数据:', currentRow);
                                    console.log('提交URL:', currentOpt);

                                    try {
                                        // 阻止默认表单提交
                                        if (data.form && data.form.preventDefault) {
                                            data.form.preventDefault();
                                        }
                                        if (event && event.preventDefault) {
                                            event.preventDefault();
                                        }

                                        console.log('表单字段keys:', Object.keys(data.field));
                                        console.log('当前行数据keys:', Object.keys(currentRow));

                                        var postData = Object.assign({}, currentRow, data.field);
                                        for (var i in postData) {    // 清除值为null的属性
                                            if (postData[i] === null) {
                                                delete postData[i];
                                            }
                                        }
                                        console.log('准备提交的数据:', postData);
                                        console.log('提交URL:', currentOpt);
                                        console.log('JSON字符串:', JSON.stringify(postData));

                                        // 验证必要数据
                                        if (!postData.ID) {
                                            layer.msg('缺少作业ID', { icon: 2 });
                                            console.error('缺少作业ID:', postData);
                                            return false;
                                        }

                                        // 根据提交类型进行不同的验证
                                        if (postData.submission_type === 'text') {
                                            if (!postData.text_content || !postData.text_content.trim()) {
                                                layer.msg('请输入文本作业内容', { icon: 2 });
                                                console.error('缺少文本内容:', postData);
                                                return false;
                                            }
                                            if (postData.text_content.trim().length < 10) {
                                                layer.msg('文本内容过短，至少需要10个字符', { icon: 2 });
                                                console.error('文本内容过短:', postData.text_content.length);
                                                return false;
                                            }
                                        } else if (postData.submission_type === 'code') {
                                            if (!postData.code || !postData.code.trim()) {
                                                layer.msg('请输入作业代码', { icon: 2 });
                                                console.error('缺少代码内容:', postData);
                                                return false;
                                            }
                                        }

                                        // 显示加载提示
                                        var loadIndex = layer.load(2, { shade: [0.1, '#fff'] });

                                        $.ajax({
                                            type: 'POST',
                                            url: currentOpt,
                                            contentType: 'application/json;charset=utf-8',
                                            dataType: 'json',
                                            data: JSON.stringify(postData),
                                            success: function (result) {
                                                layer.close(loadIndex); // 关闭加载提示
                                                console.log('提交结果:', result);

                                                try {
                                                    // 如果result是字符串，尝试解析为JSON
                                                    if (typeof result === 'string') {
                                                        result = JSON.parse(result);
                                                    }

                                                    if (result.code === 0) {
                                                        alert("提交成功");
                                                        layer.msg("提交成功！", {
                                                            icon: 1,
                                                            time: 2000,
                                                            end: function () {
                                                                try {
                                                                    table.reload('manage_table');
                                                                    layer.close(layerIndex);
                                                                } catch (e) {
                                                                    console.error('刷新表格失败:', e);
                                                                    layer.close(layerIndex);
                                                                    // 如果表格刷新失败，延迟刷新页面
                                                                    setTimeout(function () {
                                                                        if (window !== window.top) {
                                                                            window.location.reload();
                                                                        } else {
                                                                            location.reload();
                                                                        }
                                                                    }, 500);
                                                                }
                                                            }
                                                        });
                                                    } else if (result.code === 2) {
                                                        layer.msg(result.msg, {
                                                            icon: 2,
                                                            time: 3000
                                                        });
                                                    } else {
                                                        layer.msg("提交失败！");
                                                    }
                                                } catch (e) {
                                                    console.error('解析响应数据失败:', e);
                                                    layer.msg("响应数据格式错误", {
                                                        icon: 2,
                                                        time: 3000
                                                    });
                                                }
                                            },
                                            error: function (xhr, status, error) {
                                                layer.close(loadIndex); // 关闭加载提示
                                                console.error('AJAX请求失败:', xhr, status, error);
                                                console.error('响应状态:', xhr.status);
                                                console.error('响应文本:', xhr.responseText);
                                                console.error('请求URL:', currentOpt);
                                                console.error('请求数据:', JSON.stringify(postData));

                                                if (xhr.status === 403) {
                                                    layer.msg("权限不足，请重新登录", {
                                                        icon: 2,
                                                        time: 3000
                                                    });
                                                } else if (xhr.status === 401) {
                                                    layer.msg("请先登录", {
                                                        icon: 2,
                                                        time: 3000
                                                    });
                                                    setTimeout(function () {
                                                        window.location.href = '/login';
                                                    }, 1000);
                                                } else if (xhr.status === 0) {
                                                    layer.msg("网络连接失败，请检查网络", {
                                                        icon: 2,
                                                        time: 3000
                                                    });
                                                } else {
                                                    var errorMsg = "提交失败，请稍后重试";
                                                    try {
                                                        if (xhr.responseJSON && xhr.responseJSON.error) {
                                                            errorMsg += "。错误：" + xhr.responseJSON.error;
                                                        } else if (xhr.responseText) {
                                                            errorMsg += "。错误：" + xhr.responseText;
                                                        }
                                                    } catch (e) {
                                                        errorMsg += "。状态码：" + xhr.status;
                                                    }
                                                    layer.msg(errorMsg, {
                                                        icon: 2,
                                                        time: 5000
                                                    });
                                                }
                                            },
                                            timeout: 30000
                                        });
                                        return false; // 阻止表单默认提交
                                    } catch (error) {
                                        console.error('表单提交过程中发生错误:', error);
                                        layer.msg('提交过程中发生错误: ' + error.message, {
                                            icon: 2,
                                            time: 3000
                                        });
                                        return false;
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    </script>

</body>

</html>